package main

import "fmt"

// 多数元素
// https://leetcode.cn/problems/majority-element/description/?envType=study-plan-v2&envId=top-interview-150
func main() {
	nums := []int{2, 2, 1, 1, 1, 1, 1, 2, 2}
	a := majorityElement(nums)
	fmt.Println(a)
}

func majorityElement(nums []int) int {
	candidate := nums[0]
	count := 1
	for i := 1; i < len(nums); i++ {
		if nums[i] == candidate {
			count++
		} else {
			count--
			if count == 0 {
				candidate = nums[i]
				count = 1
			}
		}
	}

	return candidate
}
